package com.ml.doctor.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.ml.doctor.bean.CityBean;
import com.ml.doctor.bean.ZhiChenBean;
import com.ml.doctor.utils.DisplayUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class PickerView extends View {

    public static final String TAG = "PickerView";
    public static final int CAN_LOOP_MIN_COUNT = 7;
    /**
     * text之间间距和minTextSize之比
     */
    public static final float MARGIN_ALPHA = 1.5f;
    /**
     * 自动回滚到中间的速度
     */
    public static final float SPEED = 2;

    private List<String> mDataList;
    /**
     * 选中的位置，这个位置是mDataList的中心位置，一直不变
     */
    private int mCurrentSelected;
    private Paint mPaint;
    private Paint linePaint;

    private float mMaxTextSize = 17;
    private float mMinTextSize = 15;

    private float mMaxTextAlpha = 255;
    private float mMinTextAlpha = 120;


    private int mColorText = 0x333333;

    private int mViewHeight;
    private int mViewWidth;

    private float textSize;


    private float mLastDownY;
    /**
     * 滑动的距离
     */
    private float mMoveLen = 0;
    private boolean isInit = false;
    private OnItemSelectedListener mSelectListener;
    private Timer timer;
    private MyTimerTask mTask;

    //===控制循环
    private boolean isLoop = false;
    private int mCurrentSelectedWhenIsCycle;

    private String suffix;

    Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (Math.abs(mMoveLen) < SPEED) {
                mMoveLen = 0;
                if (mTask != null) {
                    mTask.cancel();
                    mTask = null;
                    performSelect();
                }
            } else
                // 这里mMoveLen / Math.abs(mMoveLen)是为了保有mMoveLen的正负号，以实现上滚或下滚
                mMoveLen = mMoveLen - mMoveLen / Math.abs(mMoveLen) * SPEED;
            invalidate();
        }

    };

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        updateHandler.removeCallbacksAndMessages(null);
    }

    ;

    public PickerView(Context context) {
        super(context);
        init();
    }

    public PickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setOnSelectListener(OnItemSelectedListener listener) {
        mSelectListener = listener;
    }

    public void performSelect() {
        if (mSelectListener != null)
            mSelectListener.onItemSelected(this, getSelectedText(), getSelectedIndex());
    }

    public void setList(List datas, int currentSelected) {
        if (datas == null) {
            datas = new ArrayList<>();
        }
        mDataList.clear();
        for (int i = 0; i < datas.size(); i++) {
            if (datas.get(i) instanceof CityBean.ProvinceEntity) {
                mDataList.add(((CityBean.ProvinceEntity) datas.get(i)).name);
            } else if (datas.get(i) instanceof CityBean.ProvinceEntity.CitiesEntity) {
                mDataList.add(((CityBean.ProvinceEntity.CitiesEntity) datas.get(i)).name);
            } else if (datas.get(i) instanceof CityBean.ProvinceEntity.CitiesEntity.DistrictsEntity) {
                mDataList.add(((CityBean.ProvinceEntity.CitiesEntity.DistrictsEntity) datas.get(i)).name);
            } else if (datas.get(i) instanceof ZhiChenBean) {
                mDataList.add(((ZhiChenBean) datas.get(i)).rankname);
            } else {
                mDataList.add("");
            }

        }
        if (currentSelected >= 0) {
            mCurrentSelected = currentSelected;
        } else {
            mCurrentSelected = datas.size() / 2;
        }

        mCurrentSelectedWhenIsCycle = mCurrentSelected;
        hasWrapData = false;
        invalidate();
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public String getSelectedText() {
        if (mCurrentSelected >= 0 && mCurrentSelected < mDataList.size()) {
            return mDataList.get(mCurrentSelected);
        }
        return "";
    }

    private String getTextWithSuffixByIndex(int index) {
        if (index < mDataList.size() && index >= 0) {

            return TextUtils.isEmpty(suffix) ? mDataList.get(index) : mDataList.get(index) + suffix;
        }
        return "";
    }


    public void setSelectedIndex(int selected) {
        mCurrentSelected = selected;
        if (mCurrentSelected < 0) {
            mCurrentSelected = 0;
        }
        if (mCurrentSelected > mDataList.size() - 1) {
            mCurrentSelected = mDataList.size() - 1;
        }
        mCurrentSelectedWhenIsCycle = mCurrentSelected;
        invalidate();
    }

    public int getSelectedIndex() {
        return canLoop() ? mCurrentSelectedWhenIsCycle : mCurrentSelected;
    }

    public void setNotLoop() {
        this.isLoop = false;
    }

    private boolean canLoop() {
        return isLoop && mDataList.size() >= CAN_LOOP_MIN_COUNT;
    }

    private void moveHeadToTail() {
        if (canLoop()) {
            String head = mDataList.get(0);
            mDataList.remove(0);
            mDataList.add(head);
            mCurrentSelectedWhenIsCycle++;
            while (mCurrentSelectedWhenIsCycle >= mDataList.size()) {
                mCurrentSelectedWhenIsCycle -= mDataList.size();
            }
        } else {
            mCurrentSelected++;
        }
    }

    private void moveTailToHead() {
        if (canLoop()) {
            String tail = mDataList.get(mDataList.size() - 1);
            mDataList.remove(mDataList.size() - 1);
            mDataList.add(0, tail);
            mCurrentSelectedWhenIsCycle--;
            while (mCurrentSelectedWhenIsCycle < 0) {
                mCurrentSelectedWhenIsCycle += mDataList.size();
            }
        } else {
            mCurrentSelected--;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mViewHeight = getMeasuredHeight();
        mViewWidth = getMeasuredWidth();
        // 按照View的高度计算字体大小
        mMaxTextSize = mViewHeight / 4.0f;
        mMinTextSize = mMaxTextSize / 2f;
        isInit = true;

        invalidate();
    }

    private void init() {
        timer = new Timer();
        mDataList = new ArrayList<>();
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setTextAlign(Paint.Align.CENTER);
        mPaint.setColor(mColorText);
        linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        linePaint.setStyle(Paint.Style.FILL);
        linePaint.setColor(Color.parseColor("#c4c4c4"));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 根据index绘制view
        if (isInit) {
            drawLine(canvas);
            drawData(canvas);
        }
    }

    private boolean hasWrapData;

    private void wrapDataWhenIsLoop() {
        do {
            if (!canLoop() || hasWrapData) {
                break;
            }

            int midIndex = mDataList.size() / 2;
            if (midIndex == mCurrentSelected) {
                break;
            }
            int moveLen = Math.abs(midIndex - mCurrentSelected);
            if (midIndex > mCurrentSelected) {
                for (int i = 0; i < moveLen; i++) {
                    String tail = mDataList.get(mDataList.size() - 1);
                    mDataList.remove(mDataList.size() - 1);
                    mDataList.add(0, tail);
                    mCurrentSelected++;
                }
            } else if (midIndex < mCurrentSelected) {
                for (int i = 0; i < moveLen; i++) {
                    String head = mDataList.get(0);
                    mDataList.remove(0);
                    mDataList.add(head);
                    mCurrentSelected--;
                }
            }
        } while (false);
        hasWrapData = true;
    }

    /**
     * 画上下两条线
     */
    private void drawLine(Canvas canvas) {
        canvas.drawLine(0, mViewHeight / 2 - DisplayUtils.sp2px(getContext(), 20), mViewWidth, mViewHeight / 2 - DisplayUtils.sp2px(getContext(), 20), linePaint);
        canvas.drawLine(0, mViewHeight / 2 + DisplayUtils.sp2px(getContext(), 20), mViewWidth, mViewHeight / 2 + DisplayUtils.sp2px(getContext(), 20), linePaint);
    }

    private void drawData(Canvas canvas) {
        if (isInEditMode()) {
            return;
        }
        wrapDataWhenIsLoop();
        if (!canLoop()) {
            if (mCurrentSelected < 0) {
                mCurrentSelected = 0;
            }
            if (mCurrentSelected > mDataList.size() - 1) {
                mCurrentSelected = mDataList.size() - 1;
            }
        }

        // 先绘制选中的text再往上往下绘制其余的text
        float scale = parabola(mViewHeight / 4.0f, mMoveLen);
        float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;

        //==文字大小固定begin
        size = DisplayUtils.sp2px(getContext(), 17);
        //==end

        mPaint.setTextSize(size);

        mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
        // text居中绘制，注意baseline的计算才能达到居中，y值是text中心坐标
        float x = (float) (mViewWidth / 2.0);
        float y = (float) (mViewHeight / 2.0 + mMoveLen);
        Paint.FontMetricsInt fmi = mPaint.getFontMetricsInt();
        float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));

        canvas.drawText(getTextWithSuffixByIndex(mCurrentSelected), x, baseline, mPaint);

        // 绘制上方data
        for (int i = 1; (mCurrentSelected - i) >= 0; i++) {
            drawOtherText(canvas, i, -1);
        }
        // 绘制下方data
        for (int i = 1; (mCurrentSelected + i) < mDataList.size(); i++) {
            drawOtherText(canvas, i, 1);
        }

    }

    /**
     * @param canvas
     * @param position 距离mCurrentSelected的差值
     * @param type     1表示向下绘制，-1表示向上绘制
     */
    private void drawOtherText(Canvas canvas, int position, int type) {
        float d = (float) (MARGIN_ALPHA * mMinTextSize * position + type
                * mMoveLen);

        float scale = parabola(mViewHeight / 4.0f, d);
        float size = (mMaxTextSize - mMinTextSize) * scale + mMinTextSize;

        //==文字大小固定begin
        size = DisplayUtils.sp2px(getContext(), 17);

        //==end

        mPaint.setTextSize(size);
        mPaint.setAlpha((int) ((mMaxTextAlpha - mMinTextAlpha) * scale + mMinTextAlpha));
        float y = (float) (mViewHeight / 2.0 + type * d);
        Paint.FontMetricsInt fmi = mPaint.getFontMetricsInt();

        float baseline = (float) (y - (fmi.bottom / 2.0 + fmi.top / 2.0));
        canvas.drawText(getTextWithSuffixByIndex(mCurrentSelected + type * position),
                (float) (mViewWidth / 2.0), baseline, mPaint);
    }


    /**
     * 抛物线
     *
     * @param zero 零点坐标
     * @param x    偏移量
     * @return scale
     */
    private float parabola(float zero, float x) {
        float f = (float) (1 - Math.pow(x / zero, 2));
        return f < 0 ? 0 : f;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                doDown(event);
                break;
            case MotionEvent.ACTION_MOVE:
                doMove(event);
                break;
            case MotionEvent.ACTION_UP:
                doUp(event);
                break;
        }
        return true;
    }

    private void doDown(MotionEvent event) {
        if (mTask != null) {
            mTask.cancel();
            mTask = null;
        }
        mLastDownY = event.getY();
    }

    private void doMove(MotionEvent event) {

        mMoveLen += (event.getY() - mLastDownY);

        if (!canLoop()) {
            if ((mCurrentSelected == 0 && mMoveLen > 0.0001) || (mCurrentSelected == mDataList.size() - 1 && mMoveLen < 0.0001)) {
                mMoveLen -= event.getY() - mLastDownY;
                return;
            }
        }

        if (mMoveLen > MARGIN_ALPHA * mMinTextSize / 2) {
            // 往下滑超过离开距离
            moveTailToHead();
            mMoveLen = mMoveLen - MARGIN_ALPHA * mMinTextSize;
        } else if (mMoveLen < -MARGIN_ALPHA * mMinTextSize / 2) {
            // 往上滑超过离开距离
            moveHeadToTail();
            mMoveLen = mMoveLen + MARGIN_ALPHA * mMinTextSize;
        }

        mLastDownY = event.getY();
        invalidate();
    }

    private void doUp(MotionEvent event) {
        if (!canLoop()) {
            if (mCurrentSelected < 0) {
                mCurrentSelected = 0;
            }
            if (mCurrentSelected >= mDataList.size()) {
                mCurrentSelected = mDataList.size() - 1;
            }
        }

        // 抬起手后mCurrentSelected的位置由当前位置move到中间选中位置
        if (Math.abs(mMoveLen) < 0.0001) {
            mMoveLen = 0;
            return;
        }
        if (mTask != null) {
            mTask.cancel();
            mTask = null;
        }
        mTask = new MyTimerTask(updateHandler);
        timer.schedule(mTask, 0, 10);
    }

    class MyTimerTask extends TimerTask {
        Handler handler;

        public MyTimerTask(Handler handler) {
            this.handler = handler;
        }

        @Override
        public void run() {
            handler.sendMessage(handler.obtainMessage());
        }

    }

    public interface OnItemSelectedListener {
        void onItemSelected(PickerView pickView, String text, int position);
    }
}
